import { HTTP_STATUS } from "#src/constants/http.constants.js";
import { API_STATUS } from "#src/constants/api.constants.js";
import { logger } from '#src/common/utils/logger.js';
import { CommonMessage } from '#src/constants/message.constants.js';

/**
 * 响应处理类
 * 整合了响应消息与响应处理逻辑
 */
export class ResponseHandler {
    /**
     * 处理数据，提取data属性（如果存在）
     * @private
     * @param {*} data - 要处理的数据
     * @returns {*} 处理后的数据
     */
    static _processData(data) {
        return data?.data || data;
    }

    /**
     * 发送响应
     * @param {Object} res - Express响应对象
     * @param {*} data - 响应数据
     * @param {string} message - 响应消息
     * @param {number} httpCode - HTTP状态码
     * @param {Object} context - 日志上下文
     * @returns {Object} Express响应
     */
    static send(res, data, message, httpCode, context = {}) {
        const response = {
            code: httpCode >= 200 && httpCode < 300 ? API_STATUS.SUCCESS : API_STATUS.ERROR,
            message,
        };

        if (data !== null) {
            response.data = data;
        }

        logger.http('API响应', { ...context, response, httpCode });
        return res.status(httpCode).json(response);
    }

    /**
     * 成功响应
     * @param {*} data - 响应数据
     * @param {string} message - 响应消息
     * @returns {Object} 响应对象
     */
    static success(data = null, message = CommonMessage.SUCCESS) {
        const response = {
            code: API_STATUS.SUCCESS,
            message,
        };

        const processedData = this._processData(data);
        if (processedData !== null) {
            response.data = processedData;
        }

        return response;
    }

    /**
     * 错误响应
     * @param {string} message - 错误消息
     * @param {number} httpCode - HTTP状态码
     * @returns {Object} 错误响应对象
     */
    static error(message = CommonMessage.ERROR, httpCode = HTTP_STATUS.BAD_REQUEST) {
        return {
            code: API_STATUS.ERROR,
            message
        };
    }

    /**
     * 创建成功响应
     * @param {Object} res - Express响应对象
     * @param {*} data - 响应数据
     * @param {string} message - 响应消息
     * @returns {Object} Express响应
     */
    static sendSuccess(res, data = null, message = CommonMessage.SUCCESS) {
        return this.send(res, data, message, HTTP_STATUS.OK);
    }

    /**
     * 创建已创建响应
     * @param {Object} res - Express响应对象
     * @param {*} data - 响应数据
     * @param {string} message - 响应消息
     * @returns {Object} Express响应
     */
    static sendCreated(res, data = null, message = CommonMessage.SUCCESS) {
        return this.send(res, data, message, HTTP_STATUS.CREATED);
    }

    /**
     * 创建错误响应
     * @param {Object} res - Express响应对象
     * @param {string} message - 错误消息
     * @param {number} httpCode - HTTP状态码
     * @returns {Object} Express响应
     */
    static sendError(res, message = CommonMessage.ERROR, httpCode = HTTP_STATUS.BAD_REQUEST) {
        return this.send(res, null, message, httpCode);
    }
}
